//
//  OAuthViewController.swift
//  weibo
//
//  Created by 谭仁川 on 15/11/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    
    
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func defaultAccount(){
        let jsString = "document.getElementById('userId').value = '18698991463', document.getElementById('passwd').value = 'My0125' "
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)

    }
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")

    
         loadOAuthPage()
    }

    private func loadOAuthPage(){
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        if let url = NSURL(string: urlString){
            let request = NSURLRequest(URL: url)
            webView.loadRequest(request)
        }
    
    }


}

extension OAuthViewController:UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
       }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        let urlString = request.URL?.absoluteString ?? ""
        
        if urlString.hasPrefix("https://api.weibo.com/"){
            return true
        }
        if !urlString.hasPrefix("http://www.baidu.com"){
        
            return false
        }
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
      
        
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
        }
        
        self.dismissViewControllerAnimated((false)) { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
            
            print("come here")
        }

        
        return false
    }
    
}